// pages/home/home-nav/personal-overview/bpl/index.ts
import { getWeekValue, getChartDay, getSBPDay, getDBPDay, getGapDay, getAbnormalDay, getRecordDay, getChartWeek, getSBPWeek, getDBPWeek, getGapWeek, getAbnormalWeek, getRecordWeek, getChartMonth, getSBPMonth, getDBPMonth, getGapMonth, getAbnormalMonth, getRecordMonth } from '../../../../../utils/api/BPLControl'
import userBaseInfoState from '../../../../../stores/userBaseInfo'
import AbnormalBPLInfo from '../../../../../stores/AbnormalBPLInfo'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentStatus: 'week',
    weekClass: 'bpl-active',
    monthClass: 'bpl-normal',
    dayClass: 'bpl-normal',
    dateShow: false,
    currentDate: new Date().getTime(),
    pathDate: '0000-00-00',
    minDate: new Date(2000, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    formatter(type: string, value: any) {
      if (type === 'year') {
        return `${value}年`;
      }
      if (type === 'month') {
        return `${value}月`;
      }
      return value;
    },
    weekValue: '7月22日-7月28日',
    monthValue: '2024年7月',
    dayValue: '2024年',
    trunLeft: '<',
    user: {
      name: '熊翱',
      riskLevel: {
        normal: 1,
        low: 1,
        light: 2,
        middle: 1,
        high: 2,
        all: 7,
      },
      averageSBP: 131,
      averageDBP: 88,
    },
    SBP: {
      max: '0/0',
      maxClass: 'badge-normal',
      maxLevel: '正常',
      min: '0/0',
      minClass: 'badge-normal',
      minLevel: '正常',
      average: '0',
    },
    DBP: {
      max: '0/0',
      maxClass: 'badge-normal',
      maxLevel: '正常',
      min: '0/0',
      minClass: 'badge-normal',
      minLevel: '正常',
      average: '0',
    },
    GAP: {
      max: '0/0',
      maxClass: 'badge-normal',
      maxLevel: '正常',
      min: '0/0',
      minClass: 'badge-normal',
      minLevel: '正常',
      average: '0',
    },
  },

  changeStatus(e: any) {
    if (e.currentTarget.dataset.status !== this.data.currentStatus) {
      console.log('需要切换页面');
      if (this.data.currentStatus === 'day') {
        this.setData({ dayClass: 'bpl-normal' });
      }
      else if (this.data.currentStatus === 'week') {
        this.setData({ weekClass: 'bpl-normal' });
      }
      else {
        this.setData({ monthClass: 'bpl-normal' });
      }
      this.setData({ currentStatus: e.currentTarget.dataset.status })
      if (this.data.currentStatus === 'day') {
        this.setData({ dayClass: 'bpl-active' });
        console.log('现在是日');
        this.updateDayData();
      }
      else if (this.data.currentStatus === 'week') {
        this.setData({ weekClass: 'bpl-active' });
        console.log('现在是周');
        this.updateWeekData();
      }
      else {
        this.setData({ monthClass: 'bpl-active' });
        console.log('现在是月');
        this.updateMonthData();
      }
    }
    else {
      console.log('不需要切换页面');
    }
  },

  addBPL() {
    console.log('添加记录');
    wx.navigateTo({
      url: './add-bpl/index'
    })
  },

  loadData() {
    let now = new Date();
    let minDate = new Date(now.getFullYear() - 1, now.getMonth(), now.getDate());
    let dayValue = (now.getMonth() + 1) + '月' + (now.getDate()) + '日';
    let monthValue = (now.getFullYear()) + '年' + (now.getMonth() + 1) + '月';
    const formattedDate = now.getFullYear() + '-' +
      String(now.getMonth() + 1).padStart(2, '0') + '-' +
      String(now.getDate()).padStart(2, '0') as string;
    getWeekValue(formattedDate).then((res: any) => {
      let weekValue = res.data;
      this.setData({
        weekValue: weekValue,
      })
    }).catch((err: any) => {
      console.log('获取当周范围错误', err);
    })
    this.setData({
      pathDate: formattedDate,
      minDate: minDate.getTime(),
      dayValue: dayValue,
      monthValue: monthValue,
    })
    this.updateWeekData();
  },

  onInput(event: any) {
    this.setData({
      currentDate: event.detail,
    });
  },

  onConfirm(event: any) {
    console.log(event);
    let timeStamp = event.detail;
    let date = new Date(timeStamp);
    let dayValue = (date.getMonth() + 1) + '月' + (date.getDate()) + '日';
    let monthValue = (date.getFullYear()) + '年' + (date.getMonth() + 1) + '月';
    const formattedDate = date.getFullYear() + '-' +
      String(date.getMonth() + 1).padStart(2, '0') + '-' +
      String(date.getDate()).padStart(2, '0') as string;

    getWeekValue(formattedDate).then((res: any) => {
      let weekValue = res.data;
      this.setData({
        weekValue: weekValue,
      })
    }).catch((err: any) => {
      console.log('获取当周范围错误', err);
    })

    this.setData({
      dateShow: false,
      pathDate: formattedDate,
      dayValue: dayValue,
      monthValue: monthValue,
    })
    if (this.data.currentStatus === 'day') {
      this.setData({ dayClass: 'bpl-active' });
      console.log('现在是日');
      this.updateDayData();
    }
    else if (this.data.currentStatus === 'week') {
      this.setData({ weekClass: 'bpl-active' });
      console.log('现在是周');
      this.updateWeekData();
    }
    else {
      this.setData({ monthClass: 'bpl-active' });
      console.log('现在是月');
      this.updateMonthData();
    }
  },


  letDateShow() {
    this.setData({
      dateShow: true,
    })
  },

  dateClose() {
    this.setData({ dateShow: false });
  },

  getClass(level: string) {
    let className = 'badge-normal';
    if (level === '正常') {
      className = 'badge-normal';
      return className;
    }
    if (level === '偏低' || level === '过小') {
      className = 'badge-low';
      return className;
    }
    if (level === '轻度') {
      className = 'badge-light';
      return className;
    }
    if (level === '中度') {
      className = 'badge-middle';
      return className;
    }
    if (level === '重度' || level === '过大') {
      className = 'badge-high';
      return className;
    }
    if (level === '正常高值') {
      className = 'badge-moderate';
      return className;
    }
    return className;
  },

  updateDayData() {
    const data = {
      patientUid: userBaseInfoState.data.patientUid,
      date: this.data.pathDate,
    }
    getChartDay(data).then((res: any) => {
      console.log('日图返回', res);
      let categories: string[] = [];
      let data: [number | null, number | null][] = [];
      if (res.data.length !== 0) {
        res.data.forEach((entry: any) => {
          // 将日期添加到 categories 数组中
          const time = entry.time.substring(12, 16);
          categories.push(time);
  
          // 将高压和低压数据添加到 data 数组中
          data.push([entry.systolic, entry.diastolic]);
        });
      }
      else {
        categories = ['00:00', '23:59'];
        data = [[0, 0], [0, 0]];
      }
      let chartData = <ChartData>{
        categories: categories,
        data: data,
      }
      console.log(chartData);
      let chart = this.selectComponent('#BPLChart');
      chart.updateData(chartData);
    }).catch((err: any) => {
      console.log('请求周图数据失败', err);
    })

    getSBPDay(data).then((res: any) => {
      let max = res.data.max_systolic + '/' + res.data.max_diastolic as string;
      let maxLevel = res.data.max_syst_risk;
      let maxClass = this.getClass(maxLevel);
      let min = res.data.min_systolic + '/' + res.data.min_diastolic as string;
      let minLevel = res.data.min_syst_risk;
      let minClass = this.getClass(minLevel);
      let averageData = res.data.avg_systolic as number;
      let average = averageData.toFixed(2) as string;
      let SBP = {
        max: max,
        maxClass: maxClass,
        maxLevel: maxLevel,
        min: min,
        minClass: minClass,
        minLevel: minLevel,
        average: average,
      }
      this.setData({
        SBP: SBP,
      })
    }).catch((err: any) => {
      console.log('请求收缩压数据失败', err);
    })

    getDBPDay(data).then((res: any) => {
      console.log('请求舒张压成功', res);
      let max = res.data.max_diastolic + '/' + res.data.max_systolic as string;
      let maxLevel = res.data.max_dias_risk;
      let maxClass = this.getClass(maxLevel);
      let min = res.data.min_diastolic + '/' + res.data.min_systolic as string;
      let minLevel = res.data.min_dias_risk;
      let minClass = this.getClass(minLevel);
      let averageData = res.data.avg_diastolic as number;
      let average = averageData.toFixed(2) as string;
      let DBP = {
        max: max,
        maxClass: maxClass,
        maxLevel: maxLevel,
        min: min,
        minClass: minClass,
        minLevel: minLevel,
        average: average,
      }
      this.setData({
        DBP: DBP,
      })
    }).catch((err: any) => {
      console.log('请求舒张压数据失败', err);
    })

    getGapDay(data).then((res: any) => {
      console.log('请求舒张压成功', res);
      let max = res.data.max_pulse_pressure + ' (' + res.data.max_pulse_pressure_systolic + '/' + res.data.max_pulse_pressure_diastolic + ')' as string;
      let maxLevel = res.data.max_pulse_pressure_state;
      let maxClass = this.getClass(maxLevel);
      let min = res.data.min_pulse_pressure + ' (' + res.data.min_pulse_pressure_systolic + '/' + res.data.min_pulse_pressure_diastolic + ')' as string;
      let minLevel = res.data.min_pulse_pressure_state;
      let minClass = this.getClass(minLevel);
      let averageData = res.data.avg_pulse_pressure as number;
      let average = averageData.toFixed(2) as string;
      let GAP = {
        max: max,
        maxClass: maxClass,
        maxLevel: maxLevel,
        min: min,
        minClass: minClass,
        minLevel: minLevel,
        average: average,
      }
      this.setData({
        GAP: GAP,
      })
    }).catch((err: any) => {
      console.log('请求舒张压数据失败', err);
    })

    getAbnormalDay(data).then((res: any) => {
      let all = res.data['重度'] + res.data['中度'] + res.data['轻度'] + res.data['正常高值'] + res.data['偏低'];
      this.setData({
        'user.riskLevel.high': res.data['重度'],
        'user.riskLevel.middle': res.data['中度'],
        'user.riskLevel.light': res.data['轻度'],
        'user.riskLevel.normal': res.data['正常高值'],
        'user.riskLevel.low': res.data['偏低'],
        'user.riskLevel.all': all,
      });
    }).catch((err: any) => {
      console.log('请求舒张压数据失败', err);
    })

    getRecordDay(data).then((res: any) => {
      console.log('获取的数据列表是', res);
      const newData: AbnormalBplInfo[] = res.data.map((item: any) => ({
        systolic: item.systolic,
        diastolic: item.diastolic,
        riskLevel: item.risk,
        uploadTime: item.time,
      }));
      AbnormalBPLInfo.onChangeData(newData);
    })
  },

  updateWeekData() {
    console.log('目前路径日期是', this.data.pathDate);
    const data = {
      patientUid: userBaseInfoState.data.patientUid,
      anyDateInWeek: this.data.pathDate,
    }
    getChartWeek(data).then((res: any) => {
      const categories: string[] = [];
      const data: [number | null, number | null][] = [];
      res.data.forEach((entry: any) => {
        // 将日期添加到 categories 数组中
        categories.push(entry.date);

        // 将高压和低压数据添加到 data 数组中
        data.push([entry.avg_systolic, entry.avg_diastolic]);
      });
      let chartData = <ChartData>{
        categories: categories,
        data: data,
      }
      console.log(chartData);
      let chart = this.selectComponent('#BPLChart');
      chart.updateData(chartData);
    }).catch((err: any) => {
      console.log('请求周图数据失败', err);
    })

    getSBPWeek(data).then((res: any) => {
      let max = res.data.max_systolic + '/' + res.data.max_diastolic as string;
      let maxLevel = res.data.max_syst_risk;
      let maxClass = this.getClass(maxLevel);
      let min = res.data.min_systolic + '/' + res.data.min_diastolic as string;
      let minLevel = res.data.min_syst_risk;
      let minClass = this.getClass(minLevel);
      let averageData = res.data.avg_systolic as number;
      let average = averageData.toFixed(2) as string;
      let SBP = {
        max: max,
        maxClass: maxClass,
        maxLevel: maxLevel,
        min: min,
        minClass: minClass,
        minLevel: minLevel,
        average: average,
      }
      this.setData({
        SBP: SBP,
      })
    }).catch((err: any) => {
      console.log('请求收缩压数据失败', err);
    })

    getDBPWeek(data).then((res: any) => {
      console.log('请求舒张压成功', res);
      let max = res.data.max_diastolic + '/' + res.data.max_systolic as string;
      let maxLevel = res.data.max_dias_risk;
      let maxClass = this.getClass(maxLevel);
      let min = res.data.min_diastolic + '/' + res.data.min_systolic as string;
      let minLevel = res.data.min_dias_risk;
      let minClass = this.getClass(minLevel);
      let averageData = res.data.avg_diastolic as number;
      let average = averageData.toFixed(2) as string;
      let DBP = {
        max: max,
        maxClass: maxClass,
        maxLevel: maxLevel,
        min: min,
        minClass: minClass,
        minLevel: minLevel,
        average: average,
      }
      this.setData({
        DBP: DBP,
      })
    }).catch((err: any) => {
      console.log('请求舒张压数据失败', err);
    })

    getGapWeek(data).then((res: any) => {
      console.log('请求舒张压成功', res);
      let max = res.data.max_pulse_pressure + ' (' + res.data.max_pulse_pressure_systolic + '/' + res.data.max_pulse_pressure_diastolic + ')' as string;
      let maxLevel = res.data.max_pulse_pressure_state;
      let maxClass = this.getClass(maxLevel);
      let min = res.data.min_pulse_pressure + ' (' + res.data.min_pulse_pressure_systolic + '/' + res.data.min_pulse_pressure_diastolic + ')' as string;
      let minLevel = res.data.min_pulse_pressure_state;
      let minClass = this.getClass(minLevel);
      let averageData = res.data.avg_pulse_pressure as number;
      let average = averageData.toFixed(2) as string;
      let GAP = {
        max: max,
        maxClass: maxClass,
        maxLevel: maxLevel,
        min: min,
        minClass: minClass,
        minLevel: minLevel,
        average: average,
      }
      this.setData({
        GAP: GAP,
      })
    }).catch((err: any) => {
      console.log('请求舒张压数据失败', err);
    })

    getAbnormalWeek(data).then((res: any) => {
      let all = res.data['重度'] + res.data['中度'] + res.data['轻度'] + res.data['正常高值'] + res.data['偏低'];
      this.setData({
        'user.riskLevel.high': res.data['重度'],
        'user.riskLevel.middle': res.data['中度'],
        'user.riskLevel.light': res.data['轻度'],
        'user.riskLevel.normal': res.data['正常高值'],
        'user.riskLevel.low': res.data['偏低'],
        'user.riskLevel.all': all,
      });
    }).catch((err: any) => {
      console.log('请求舒张压数据失败', err);
    })

    const newData = {
      patientUid: userBaseInfoState.data.patientUid,
      date: this.data.pathDate,
    }

    getRecordWeek(newData).then((res: any) => {
      console.log('获取的数据列表是', res);
      const newData: AbnormalBplInfo[] = res.data.map((item: any) => ({
        systolic: item.systolic,
        diastolic: item.diastolic,
        riskLevel: item.risk,
        uploadTime: item.time,
      }));
      AbnormalBPLInfo.onChangeData(newData);
    })
  },

  updateMonthData() {
    const data = {
      patientUid: userBaseInfoState.data.patientUid,
      month: this.data.pathDate.substring(0, 7),
    }
    console.log('月的data', data);
    getChartMonth(data).then((res: any) => {
      console.log('月图返回', res);
      const categories: string[] = [];
      const data: [number | null, number | null][] = [];
      res.data.forEach((entry: any) => {
        // 将日期添加到 categories 数组中
        categories.push(entry.start_date);

        // 将高压和低压数据添加到 data 数组中
        data.push([entry.avg_systolic, entry.avg_diastolic]);
      });
      let chartData = <ChartData>{
        categories: categories,
        data: data,
      }
      console.log(chartData);
      let chart = this.selectComponent('#BPLChart');
      chart.updateData(chartData);
    }).catch((err: any) => {
      console.log('请求月图数据失败', err);
    })

    getSBPMonth(data).then((res: any) => {
      let max = res.data.max_systolic + '/' + res.data.max_diastolic as string;
      let maxLevel = res.data.max_syst_risk;
      let maxClass = this.getClass(maxLevel);
      let min = res.data.min_systolic + '/' + res.data.min_diastolic as string;
      let minLevel = res.data.min_syst_risk;
      let minClass = this.getClass(minLevel);
      let averageData = res.data.avg_systolic as number;
      let average = averageData.toFixed(2) as string;
      let SBP = {
        max: max,
        maxClass: maxClass,
        maxLevel: maxLevel,
        min: min,
        minClass: minClass,
        minLevel: minLevel,
        average: average,
      }
      this.setData({
        SBP: SBP,
      })
    }).catch((err: any) => {
      console.log('请求收缩压数据失败', err);
    })

    getDBPMonth(data).then((res: any) => {
      console.log('请求舒张压成功', res);
      let max = res.data.max_diastolic + '/' + res.data.max_systolic as string;
      let maxLevel = res.data.max_dias_risk;
      let maxClass = this.getClass(maxLevel);
      let min = res.data.min_diastolic + '/' + res.data.min_systolic as string;
      let minLevel = res.data.min_dias_risk;
      let minClass = this.getClass(minLevel);
      let averageData = res.data.avg_diastolic as number;
      let average = averageData.toFixed(2) as string;
      let DBP = {
        max: max,
        maxClass: maxClass,
        maxLevel: maxLevel,
        min: min,
        minClass: minClass,
        minLevel: minLevel,
        average: average,
      }
      this.setData({
        DBP: DBP,
      })
    }).catch((err: any) => {
      console.log('请求舒张压数据失败', err);
    })

    getGapMonth(data).then((res: any) => {
      console.log('请求舒张压成功', res);
      let max = res.data.max_pulse_pressure + ' (' + res.data.max_pulse_pressure_systolic + '/' + res.data.max_pulse_pressure_diastolic + ')' as string;
      let maxLevel = res.data.max_pulse_pressure_state;
      let maxClass = this.getClass(maxLevel);
      let min = res.data.min_pulse_pressure + ' (' + res.data.min_pulse_pressure_systolic + '/' + res.data.min_pulse_pressure_diastolic + ')' as string;
      let minLevel = res.data.min_pulse_pressure_state;
      let minClass = this.getClass(minLevel);
      let averageData = res.data.avg_pulse_pressure as number;
      let average = averageData.toFixed(2) as string;
      let GAP = {
        max: max,
        maxClass: maxClass,
        maxLevel: maxLevel,
        min: min,
        minClass: minClass,
        minLevel: minLevel,
        average: average,
      }
      this.setData({
        GAP: GAP,
      })
    }).catch((err: any) => {
      console.log('请脉压差数据失败', err);
    })

    getAbnormalMonth(data).then((res: any) => {
      let all = res.data['重度'] + res.data['中度'] + res.data['轻度'] + res.data['正常高值'] + res.data['偏低'];
      this.setData({
        'user.riskLevel.high': res.data['重度'],
        'user.riskLevel.middle': res.data['中度'],
        'user.riskLevel.light': res.data['轻度'],
        'user.riskLevel.normal': res.data['正常高值'],
        'user.riskLevel.low': res.data['偏低'],
        'user.riskLevel.all': all,
      });
    }).catch((err: any) => {
      console.log('请求月异常数据失败', err);
    })

    getRecordMonth(data).then((res: any) => {
      console.log('获取的数据列表是', res);
      const newData: AbnormalBplInfo[] = res.data.map((item: any) => ({
        systolic: item.systolic,
        diastolic: item.diastolic,
        riskLevel: item.risk,
        uploadTime: item.time,
      }));
      AbnormalBPLInfo.onChangeData(newData);
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    this.loadData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (this.data.currentStatus === 'day') {
      this.setData({ dayClass: 'bpl-active' });
      console.log('现在是日');
      this.updateDayData();
    }
    else if (this.data.currentStatus === 'week') {
      this.setData({ weekClass: 'bpl-active' });
      console.log('现在是周');
      this.updateWeekData();
    }
    else {
      this.setData({ monthClass: 'bpl-active' });
      console.log('现在是月');
      this.updateMonthData();
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})